package com.swx.guard.util;

import lombok.SneakyThrows;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.StringReader;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.util.Properties;

/**
 * @author Ricky
 * @date 2020/12/4
 */
public class PropertiesUtil {

    @SneakyThrows
    public static <T> T getUpdateConfig(File file, Class<T> tClass) {
        String propertiesString = FileUtils.readFileToString(file, StandardCharsets.UTF_8);
        return getUpdateConfig(propertiesString, tClass);
    }

    @SneakyThrows
    public static <T> T getUpdateConfig(String propertiesString, Class<T> tClass) {
        Properties properties = new Properties();
        properties.load(new StringReader(propertiesString));
        T t = tClass.newInstance();
        Field[] declaredFields = tClass.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            String name = declaredField.getName();
            String value = properties.getProperty(name);
            String methodName = "set" + name.substring(0, 1).toUpperCase() + name.substring(1);
            Method method = tClass.getMethod(methodName, String.class);
            method.invoke(t, value);
        }
        return t;
    }

    public static void saveObjToProperties(Object obj, String filePath) {
        Properties prop = new Properties();
        try {
            Class<?> aClass = obj.getClass();
            Field[] declaredFields = aClass.getDeclaredFields();
            for (Field declaredField : declaredFields) {
                String name = declaredField.getName();
                String methodName = "get" + name.substring(0, 1).toUpperCase() + name.substring(1);
                Method method = aClass.getMethod(methodName);
                Object value = method.invoke(obj);
                if (value == null) {
                    value = "";
                }
                prop.setProperty(name, (String) value);
            }
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }

        try (FileOutputStream fileOutputStream = new FileOutputStream(filePath)) {
            prop.store(fileOutputStream, "");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
